<template>
  <Teleport to="body">
    <div class="feedback">
      <el-popover
        :visible="visible"
        trigger="manual"
        placement="left"
        popper-class="custom-popover"
        :popper-style="{ width: '500px', height: '650px' }"
        propper-style=""
      >
        <el-main>
          <div class="mainContent">
            <div class="timeline-container">
              <el-timeline>
                <el-timeline-item
                  v-for="message in messages"
                  :key="message.id"
                  :icon="message.userType === 2 ? 'User' : 'Bell'"
                  :color="message.userType === 2 ? 'blue' : 'green'"
                >
                  <span v-html="message.text"></span>
                </el-timeline-item>
              </el-timeline>
            </div>

            <el-card class="box-card">
              <el-input
                v-model="userInput"
                :rows="4"
                type="textarea"
                placeholder="请输入消息"
                @keyup.enter.native="sendMessage"
              />

              <el-button
                type="primary"
                :disabled="!userInput"
                @click="sendMessage"
                style="width: 100%; height: 50px; margin-top: 10px"
              >
                发送
              </el-button>
            </el-card>
          </div>
        </el-main>
        <template #reference>
          <div class="slot-content" @click="toggleVisible">
            <ChatLineSquare class="feedback-icon" />
            <div v-if="showText" class="feedback-text">chat</div>
          </div>
        </template>
      </el-popover>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { onUnmounted, ref } from "vue";
import axios from "axios"; // 确保已安装axios
import { ChatLineSquare } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus'
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { userinfo } from '@/stores/counter'

const user = userinfo()
const visible = ref(false);
const showText = ref(false);
const messages = ref([
  { text: "对这篇文章有什么疑问吗？", id: 1, userType: 1 },
  // 可以在这里添加更多模拟消息
]);
const userInput = ref("");
const first = ref(true)
const chatId = ref(null)

const toggleVisible = () => {
  visible.value = !visible.value;
  showText.value = !showText.value;
};

const sendMessage = async () => {
  if (chatId.value == null) {
    const res = await axios.post('/api/llm/createChat', {
      articleId: user.curArticle.id
    })
    chatId.value = res.data.data
  }

  const postData = {
    message: userInput.value,
    chatId: chatId.value
  };

  messages.value.push({
    text: userInput.value,
    id: Date.now(),
    userType: 2,
  });
  userInput.value = "";

  let current = ''

  messages.value.push({
    text: current,
    id: Date.now(),
    userType: 1,
  })

  try {
    await fetchEventSource('/api/llm/streamChat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
      },
      body: JSON.stringify(postData),
      onmessage(ev) {
        // console.log('SSE message:', ev.data);
        const data = ev.data;

        // 获取最新的消息对象并更新其内容
        let latestMessage = messages.value[messages.value.length - 1];
        latestMessage.text += data;
      },
      onerror(err) {
        console.error('SSE error:', err);
        // 处理错误
      },
      onclose() {
        console.log('SSE connection closed');
        // 处理连接关闭
      },
    });
  } catch (err) {
    console.error('Error sending message:', err);
    // 处理发送消息时的错误
  }

};

</script>

<style scoped>
.feedback {
  position: fixed;
  bottom: 20px;
  right: 20px;
  cursor: pointer;
}

.feedback-icon {
  /* 在这里定义图标的样式 */
  color: orange;
  width: 48px;
  height: 48px;
}

.feedback-text {
  /* 在这里定义文本的样式 */
}

.slot-content {
  display: flex;
  align-items: center;
  /* 其他样式 */
}

::v-deep .custom-popover {
  width: 5000px; /* 您可以根据需要调整宽度 */
  height: 600px; /* 您可以根据需要调整高度 */
}

.mainContent {
  height: 80vh;
  overflow: hidden;
}

.timeline-container {
  overflow-y: scroll;
  height: calc(80vh - 260px);
}

.box-card .card-header {
  /* 卡片头部样式 */
}
</style>
